package ead.cs.service.workflow.executor;

import ead.cs.domain.Shipment;
import ead.cs.domain.alert.Message;
import ead.cs.domain.workflow.Status;
import ead.cs.repository.ShipmentRepository;
import ead.cs.service.RabbitGateway;
import ead.cs.service.workflow.StatusExecutor;
import ead.cs.service.workflow.WorkflowUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LoadedItemExecutor implements StatusExecutor<Status> {

    private static final Logger LOGGER = Logger.getLogger(LoadedItemExecutor.class);

    @Autowired
    private ShipmentRepository shipmentRepository;
    @Autowired
    private RabbitGateway rabbitGateway;

    @Override
    public void execute(String itemId) {
        //business logic to execute in LOADED
        LOGGER.info("Try to update status and save shipment by id : " + itemId);
        Shipment shipment = shipmentRepository.findOne(itemId);
        shipment.setStatus(getStatus());
        shipmentRepository.save(shipment);
        LOGGER.info("Saved shipment now try to send alerts");

        if (shipment.getDeclaration() == null || shipment.getDeclaration().getExporter() == null || shipment.getDeclaration().getExporter().getEmail() == null) {
            LOGGER.warn("Email is empty.Return without sending alert email");
            throw new RuntimeException("Email is empty.Return without sending alert email");
        }

        if (BooleanUtils.isTrue(shipment.getDeclaration().getExporter().getEmailNotification())) {
            LOGGER.info("Try to send alert email");
            Message message = createMessage(Message.MessageType.EMAIL, "Your Item has been Loaded", shipment.getDeclaration().getExporter().getEmail());
            rabbitGateway.alert(WorkflowUtils.convertToJson(message));
        }

        if (BooleanUtils.isTrue(shipment.getDeclaration().getExporter().getSmsNotification())) {
            LOGGER.info("Try to send alert SMS");
            Message message = createMessage(Message.MessageType.SMS, "Your Item has been Loaded", shipment.getDeclaration().getExporter().getPhone());
            rabbitGateway.alert(WorkflowUtils.convertToJson(message));
        }
    }

    @Override
    public Status getStatus() {
        return Status.LOADED;
    }

    private Message createMessage(Message.MessageType messageType, String content, String rec) {
        Message message = new Message();
        message.setType(messageType);
        message.setContent(content);
        message.setRecipient(rec);
        return message;
    }
}

